package com.collection;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ClassName LRU_LinkedHashMap
 * @Date 2021/5/16 19:51
 * @Author 李明杰
 * @Description LinkedHashMap实现LRU算法
 */
public class LRU_LinkedHashMap<K, V> extends LinkedHashMap<K, V> {

    private int cacheSize;

    public LRU_LinkedHashMap(int cacheSize) {
        super(16, 0.75f, true);
        this.cacheSize = cacheSize;
    }

    /**
     * 判断元素个数是否超过缓存容量(默认情况下，return false，会进行扩容。)
     * 重写该方法可以删除超出的元素，相当于LRU
     */
    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > cacheSize;
    }

    public static void main(String[] args) {
        LRU_LinkedHashMap<Integer, Integer> map = new LRU_LinkedHashMap<>(3);
        map.put(1, 1);
        map.put(2, 2);
        map.put(3, 3);
        map.put(4, 4);
        map.put(1, 1);

        System.out.println(map);

    }
}
